const debug = false
let viewer = document.getElementById('viewer')
let bookType = 'pdf'
let catelogFlag = true
//进度
let curSiteX = 0
let progress = 0
let draging = false
let limitLeft = $('.operate_low .progress')[0].offsetLeft
let limitRight = $('.operate_low .progress')[0].offsetWidth
//epub
let book = null
let rendition = null
let curStart = {index: 0}//为防止前一章直接翻到底单独处理
let rootUrl = '' //epub跳转错误时候需要替换基础路径
//pdf
let pdfProxy = {}
let totalPage = 1
let curPage = 1
let linkMap = new Map()
//status
let toc = []
let curSectionIndex = 0
let curFontSize = 0
let readerMode = 0
let fontSize = 'mini'
//查词
let iframeId  = ''
let keyword = ''
prepare()
main()

async function main(){
    const buffer = await download()
    let dataView = new DataView(buffer)
    let ints = new Uint8Array(80)
    let str = ''
    for(let i=0;i<ints.length; i++){
        let code = dataView.getUint8(i)
        str += String.fromCodePoint(code)
    }
    let file = null
    let url = ''
    if(str.toLowerCase().indexOf('epub') >= 0){
        bookType = 'epub'
        file = new File([buffer], 'ebook.epub', {type: 'application/epub+zip'})
    }else if(str.toLowerCase().indexOf('pdf') >= 0){
        bookType = 'pdf'
        file = new File([buffer], 'ebook.pdf', {type: 'application/pdf'})
    }else{
        bookType = 'unknown'
        showToast('无法识别的文件')
        return
    }
    if(file){
        url = URL.createObjectURL(file)
    }
    $('#setting_options').hide()
    if(bookType === 'pdf'){
        readPdf(url)
    }else if(bookType === 'epub'){
        readEpub(url)
    }
}
function getToken(){
    let token = ''
    if(document.cookie){
        function getcookie(objname){
            var arrstr = document.cookie.split("; ");
            for (var i = 0; i < arrstr.length; i++){
                var temp = arrstr[i].split("=");
                if (temp[0] == objname) return temp[1];
            }
        }
        token = getcookie('token')
    }
    return token
}
function download(){
    let token = getToken()
    let Authorization = 'Bearer ' + token
    let origin = location.origin
    // let origin = 'http://192.168.1.181:9010'
    let fileId = decodeURI(getQuery(location.href).fileid)
    // let source = 'http://192.168.1.181:9010/FileApi/File/Download/ForUser?fileid=2837'
    let source = ''
    if(fileId !== 'undefined'){
        source = `${origin}/FileApi/File/Download/ForUser?fileid=${fileId}`
    }
    if(debug){
        source = `http://192.168.1.181:9010/FileApi/File/Download?fileid=2837`
    }
    // source = 'http://192.168.191.1/shizhan.pdf'
    // source = 'http://ebook2.zhiyuext.com/FileApi/File/Download?fileid=3281'
    // source = 'http://ebook2.zhiyuext.com/FileApi/File/Download?fileid=1769'
    return new Promise((resolve, reject)=>{        
        let xhr = new XMLHttpRequest()
        xhr.responseType = 'arraybuffer'
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                $('#loading').hide()
                if(xhr.status === 401){
                    showToast('您没有阅览权限或登录状态已过期，请先登录')
                    setTimeout(() => {
                        location.href = '/#/login?redirect=' + encodeURI(location.href)
                    }, 1500);
                    reject({msg: '下载失败'})
                }else if(xhr.status === 200){
                    resolve(xhr.response)
                }else{
                    showToast('电子书加载失败')
                    reject({msg: '下载失败'})
                }
            }
        }
        xhr.onprogress = function(res){
            let progress = Math.floor(res.loaded / res.total * 100)
            $('#loadingPro').text('加载进度：' + progress + '%')             
        }
        xhr.open('GET', source)
        xhr.setRequestHeader('Authorization', Authorization)
        xhr.send()
    })
}
//pdf阅读器
function readPdf(url){
    // let url  = 'shizhan.pdf'                
    let loadingTask = pdfjsLib.getDocument(url)
    let canvas = document.createElement('canvas')
    canvas.id = 'canvas'
    $('body').append(canvas) 
    $('#pre').html('上一页')
    $('#next').html('下一页')
    turnPageWithClick()
    loadingTask.promise.then(function(pdf) {
        pdfProxy = pdf
        totalPage = pdf._pdfInfo.numPages
        for(let i=1;i<=totalPage;i++){
            pdfProxy.getPage(i).then(function(page){
                if(i< 3){
                    console.dir(page)
                }
                let refstr = getPageRefstr(page.ref)
                linkMap.set(refstr, i)
            })
        }
        pdf.getOutline().then(outline=>{
            if(!outline){
                //无目录
                console.log('没有目录')
                $('#spine').css('color', '#d2d3d2')
                catelogFlag = false
                return
            }
            initCatelog(outline, pdf)
            
            // outline.forEach(e=>{
            //     let linkString = pdf.getDestination(e.dest)
            //     html += `<a href="${linkString}" class="cate" >${e.title}</a>`
            // })
        })
        $('#loading').hide()
        renderPage(pdfProxy, curPage)        
        initSeeker()
        managePage()
        manageSetting()
    })
    
    function initCatelog(outline, pdf){
        function getNumberByDest(dest){
            if(dest instanceof Array){
                return linkMap.get(getPageRefstr(dest[0]))
            }
            return 1
        }
        let html = '<div style="height: 100vh;overflow:scroll;padding-top:40px;">'
        outline.forEach((e, idx)=>{
            
            let pageNumber = getNumberByDest(e.dest)
            html += `<div class="cate" data-num="${pageNumber}" onclick="turnSection(event)">${e.title}</div>`
        })
        html += '</div>'
        $('#catelog').html(html)
        $('#spine').click(e=>{
            if(!catelogFlag){
                return
            }
            $('#catelog').slideDown('fast')
        })
        //目录
        $('#catelog').click(e=>{
            $('#catelog').fadeOut()
        })
        $('#catelog .cate').click(e=>{
            $('#catelog').fadeOut()
        })
    }
    
    
    function initSeeker(){
        manageProgress()
    }
}
function renderPage(pdf, index){
    pdf.getPage(index).then(function(page){
        let scale = 1
        let viewport = page.getViewport({ scale: scale, })
        // Support HiDPI-screens.
        let outputScale = window.devicePixelRatio || 1

        let canvas = document.getElementById('canvas')
        // canvas.id = getDestinationHash(page.ref)
        canvas.style.cssText = 'margin: 0 auto;display: block;'
        viewer.appendChild(canvas)
        let context = canvas.getContext('2d')
        let rate = viewport.width / viewport.height
        let w = document.body.clientWidth
        let h = w / rate
        canvas.width = Math.floor(w * outputScale)
        canvas.height = Math.floor(h * outputScale)
        canvas.style.width = Math.floor(w) + "px"
        canvas.style.height =  Math.floor(h) + "px"

        let transform = outputScale !== 1 ? [outputScale, 0, 0, outputScale, 0, 0] : null

        let renderContext = {
            canvasContext: context,
            transform: transform,
            viewport: viewport
        }
        page.render(renderContext)
    })
}
function getPageRefstr(pageRef) {
    if (!pageRef) {
      return ''
    }
    const refStr = pageRef.gen === 0 ? `${pageRef.num}R` : `${pageRef.num}R${pageRef.gen}`
    return refStr
}
function getDestinationHash(dest) {
    if (typeof dest === "string") {
      if (dest.length > 0) {
        return getAnchorUrl(encodeURIComponent(dest))
      }
    } else if (Array.isArray(dest)) {
      const str = JSON.stringify(dest);
      if (str.length > 0) {
        return getAnchorUrl(encodeURIComponent(str))
      }
    }
    return getAnchorUrl("")
}
function getAnchorUrl(str){
    let baseUrl = ''
    return (baseUrl || "") + str
}
function turnPageWithClick(){
    $('body').on('click', function(e){
        let w = document.documentElement.clientWidth
        let clickX = e.clientX
        if(clickX / w <= 0.3){
            if(curPage > 1){
                curPage -= 1
                turnPage(curPage)
            }
        }
        if(clickX / w >= 0.7){
            if(curPage < totalPage){
                curPage += 1
                turnPage(curPage)
            }
        }
    })
}
//epub 阅读器
function readEpub(url){
    init()
    book = ePub(url, {openAs: 'epub'})
    console.log('book',book)
    book.ready.then((res)=>{
        return book.locations.generate()
    })
    rendition = book.renderTo('viewer', {
        // manager: "continuous",
        // flow: "scrolled-doc",
        flow: "scrolled",
        width: "100%",
        height: "100%"
    })
    rendition.hooks.render.register(function (view) {
        // view.contents.addScript('http://192.168.191.1/static/js/bookScript.js')
        view.contents.addScript('./bookScript.js')
    })

    rendition.on('relocated', function(location){
        curStart = location.start
        let percent = book.locations.percentageFromCfi(location.start.cfi);
        let percentage = Math.floor(percent * 100);
        if(!draging) {
            progress = percentage;
        }
        updateProgress(progress)
    })
    
    
    rendition.on('displayError', function(err){
        console.log(err)
    })
    //查词
    $('#baike').on('click', ()=>{
        $('#contextMenu').hide()
        let src = encodeURI(`https://baike.baidu.com/item/${keyword}`)    
        $('#thirdLink iframe').attr('src', src)
        $('#thirdLink').show()

    })
    $('#thirdLink iframe').on('click', (e)=>{e.stopPropagation()})
    $('#thirdLink').on('click', ()=>{
        $('#thirdLink').hide()
    })
    rendition.on('rendered', function(section){
        rootUrl = section.href
        try{
            if(rendition.views()['_views'][0]){
                iframeId = rendition.views()['_views'][0].id
            }
        }catch(err){
            console.log(err)
        }
    })
    rendition.on("selected", function(range,contents) {
        book.getRange(range).then(res=>{
            keyword = res.toString()
        })
        // let childWin = document.getElementById(iframeId).contentWindow
        // let rg = rendition.getRange(range)
    })
    rendition.themes.register("light", "../css/themes.css");
    rendition.themes.register("dark", "../css/themes.css");
    rendition.themes.select("light");

    book.loaded.navigation.then(res=>{
        $('#loading').hide()
        if(res.toc instanceof Array){
            let html = '<div style="height: 100vh;overflow:scroll;padding-top:40px;position: relative;"><img onclick="closeCatelog()" src="./static/img/close.png" style="position: absolute;top: 14px;right: 20px;width:30px;height: 30px;cursor:pointer"/>'
            res.toc.forEach(e=>{
                html += `<div class="cate" data-url="${e.href}" onclick="turnSection(event)">${e.label}</div>`
            })
            html += '</div>'
            $('#catelog').html(html)
        }
    })
    rendition.display(1)
    managePage()
    function closeCatelog(){
        $('#catelog').fadeOut()
    }
    function init(){
        //设置
        manageSetting()
        $('#spine').click(e=>{
            $('#catelog').slideDown('fast')
        })
        //目录
        $('#catelog').click(e=>{
            $('#catelog').fadeOut()
        })
        $('#catelog .cate').click(e=>{
            $('#catelog').fadeOut()
        })
        //进度
        manageProgress()
    }
    function moveProgressBar(){
        let currentLocation = rendition.currentLocation()
        let currentPage = book.locations.percentageFromCfi(currentLocation.start.cfi)
        let progress = currentPage ? Math.ceil(currentPage * 100) : 0
        updateProgress(progress)
    }
    
    
    

    
    
    
}

//通用操作
function prepare(){
    $('#operate').on('click', function(e){
        e.stopPropagation()
    })
    $('#setting_options').on('click', function(e){
        e.stopPropagation()
    })
}

function turnSection(event){
    event.stopPropagation()
    if(bookType === 'epub'){
        let prevHref = ''
        let url = event.target.dataset.url
        // let reg = /^(([a-z]+\/)+)?(.+\.x?html)$/ig
        // prevHref = rootUrl.replace(reg, '$1')
        // console.log(rootUrl,prevHref, url)
        rendition.display(prevHref + url)
    }else{
        curPage = event.target.dataset.num * 1
        turnPage(curPage)
    }
}
function turnPage(index){
    renderPage(pdfProxy, index)
    let progress = Math.round(index / totalPage * 100)
    updateProgress(progress)
}
//选区菜单
$('body').on('click', lockOut)
$('#contextMenu').on('click', (e)=>{
    e.stopPropagation()
})
function lockOut(){
    $('#contextMenu').hide()
}
function lockOn(x, y){
    if(bookType === 'ebpub'){
        $('#contextMenu').css({left: `${x-30}px`, top: `${y-48}px`}).show()
    }
}
function collectBook(){
    let query = getQuery(location.href)
    const data = {
        readerId: query.readerid,
        readerUuid: query.readeruuid,
        userType: query.usertype,
        eBookId: query.ebookid,
        addOrRemove: 1,
        fromwhat: 3
    }
    fetch('http://ebook2.zhiyuext.com/EBookApi/ReaderEBookShelf/AddOrRemove', {
        method: 'POST',
        headers:{
            'Authorization': 'Bearer ' + query.token,
            'Content-Type': 'application/json' 
        },
        body: JSON.stringify(data)
    }).then(res=>{
        showToast('已添加到书架')
    }).catch(err=>{
        showToast('添加失败')
    })
}
function showToast(msg){
    let toast = document.createElement('div')
    toast.className = 'cus_toast'
    toast.style.cssText = `position: fixed;
                            width: 70%;
                            text-align: center;
                            padding: 12px 20px;
                            border-radius: 6px;
                            word-break: break-all;
                            background: rgba(0,0,0,0.6);
                            color: white;
                            top: 30%;
                            left: 50%;
                            transform: translate(-50%, -50%)`
    $(toast).html(msg)
    $('body').append(toast)
    setTimeout(()=>{
        $(toast).remove()
        toast = null
    }, 1500)                    
}
function getQuery(str){
    if(!/\?/.test(str)){
        return false
    }
    str = decodeURI(str)
    let queryString = str.split('?')[1]
    let querys = queryString.split('&')
    let obj = {}
    querys.forEach(e => {
        let arr = e.split('=')
        obj[arr[0]] = arr[1]
    })
    return obj
} 
function throttle(fn,wait){
    let timer = null;
    return function(){
        let context = this;
        let args = arguments;
        if(!timer){
            timer = setTimeout(function(){
                fn.apply(context,args);
                timer = null;
            },wait)
        }
    }
}
function manageProgress(){
    $('.fastener').on('touchstart',function(e){
        draging = true
        curSiteX = e.touches[0].clientX
    })
    $('.fastener').on('mousedown',function(e){
        console.log(e)
        draging = true
        curSiteX = e.clientX
    })
    $('.fastener').on('touchmove',function(e){
        if(!draging){
            return
        }
        let dx = e.touches[0].clientX - limitLeft
        if(dx < 0){
            dx = 0
        }
        if(dx > limitRight){
            dx = limitRight
        }
        progress = Math.ceil(dx / limitRight * 100)
        updateProgress(progress, dx)
        
    })
    $('.progress').on('mousemove',function(e){
        if(!draging){
            return
        }
        let dx = e.clientX - limitLeft
        if(dx < 0){
            dx = 0
        }
        if(dx > limitRight){
            dx = limitRight
        }
        progress = Math.ceil(dx / limitRight * 100)
        updateProgress(progress, dx)
        
    })
    $('.fastener').on('touchend',function(e){
        if(!draging){
            return
        }
        if(bookType === 'epub'){
            let cfi = book.locations.cfiFromPercentage(progress / 100);
            rendition.display(cfi);    
        }else{
            // let percentage =  progress / 100
            // $('#viewer')[0].scrollTop = $('#viewer')[0].scrollHeight * percentage
            curPage = Math.round(totalPage * progress / 100)
            if(curPage < 1){
                curPage = 1
            }
            if(curPage > totalPage){
                curPage = totalPage
            }
            renderPage(pdfProxy, curPage)
        }  
        draging = false            
    })
    $('.progress').on('mouseup',function(e){
        if(!draging){
            return
        }
        if(bookType === 'epub'){
            let cfi = book.locations.cfiFromPercentage(progress / 100);
            rendition.display(cfi);    
        }else{
            // let percentage =  progress / 100
            // $('#viewer')[0].scrollTop = $('#viewer')[0].scrollHeight * percentage
            curPage = Math.round(totalPage * progress / 100)
            if(curPage < 1){
                curPage = 1
            }
            if(curPage > totalPage){
                curPage = totalPage
            }
            renderPage(pdfProxy, curPage)
        }  
        draging = false            
    })
    $('.fastener').on('touchleave',function(e){
        draging = false
    })
    $('.progress').on('mouseleave',function(e){
        draging = false
    })
    $('.fastener').on('touchcancel',function(e){
        draging = false
    })
}

function updateProgress(progress, dx){
    //进度更新
    if(typeof dx !== 'number'){
        dx = Math.ceil(limitRight * progress / 100)
    }
    $('.fastener').css('transform', `translateX(${dx}px)`)
    $('.trunk').css('width', `${progress}%`)
    $('#percentage').html(progress)
}

function managePage(){
    $('#pre').on('click', (e)=>{
        if(bookType === 'epub'){
            if(!curStart.index){
                return
            }
            rendition.display(curStart.index - 1)
            // rendition.prev()
            e.preventDefault()
        }else{
            if(curPage > 1){
                curPage -= 1
                turnPage(curPage)
            }
        }
    })
    $('#next').on('click', (e)=>{
        if(bookType === 'epub'){
            rendition.next()
            e.preventDefault()
        }else{
            if(curPage < totalPage){
                curPage += 1
                turnPage(curPage)
            }
        }
    })
}
function manageSetting(){
    console.log('bookType')
    if(bookType === 'pdf'){
        $('#setting').css('color', '#d2d3d2')
        return
    }
    $('#setting').click(e=>{
        $('#setting_options').toggle()
    })
    $('.setting_row .font').click(function(){
        $(this).addClass('act').siblings().removeClass('act')
            if(bookType === 'epub'){
            curFontSize = $('.setting_row .font').index(this)
            if(curFontSize === 0){
                rendition.themes.fontSize("100%")
            }else if(curFontSize === 1){
                rendition.themes.fontSize("120%")
            }else{
                rendition.themes.fontSize("150%")
            }
        }
        $('#setting_options').toggle()
    })
    $('.setting_row .mode').click(function(){
        $(this).addClass('act').siblings().removeClass('act')
        if(bookType === 'epub'){
            readerMode = $('.setting_row .mode').index(this)
            if(readerMode === 0){
                rendition.themes.select('light')
            }else{
                rendition.themes.select('dark')
            }
        }
    })

    //添加、移出书架
    $('.cancelBtn').click(function(){
        $('.dialog').hide()
    })
    $('.confirmBtn').click(function(){
        $('.dialog').hide()
        //移出书架 待定
    })
    $('.removeBook').click(function(){
        $('.dialog').show()
    })
}